package controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.ProductService;

@Controller
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping("/productList")
    public String productList() {
        return "user/admin/product_list";
    }

    @RequestMapping("/inventoryList")
    public String inventoryList() {
        return "user/admin/admin_inventory_update";
    }

    @RequestMapping("/supplierList")
    public String supplierList() {
        return "user/admin/supplier_list";
    }

    @RequestMapping("/admin/admin_product_add")
    public String admin_product_add() {
        return "user/admin/admin_product_add";
    }

    @RequestMapping("/admin/admin_supplier_add")
    public String admin_supplier_add() {
        return "user/admin/admin_supplier_add";
    }

    /**
     * 商品展示
     *
     * @return 商品列表页面
     */
    // 接收登录表单请求
    @RequestMapping("/doListOfProduct")
    public ModelAndView doListOfProduct() {
        ModelAndView modelAndView = new ModelAndView();
        List<Product> product = productService.showProduct();
        modelAndView.setViewName("user/admin/product_list");
        modelAndView.addObject("list", product);
        System.out.println(product);
        return modelAndView;
    }

    /**
     * 采购记录展示
     *
     * @return 采购记录展示页面
     */
    // 接收登录表单请求
    @RequestMapping("/doPurchaseRecord")
    public ModelAndView doPurchaseRecord() {
        ModelAndView modelAndView = new ModelAndView();
        List<Purchase> purchases = productService.showPurchaseRecord();
        modelAndView.setViewName("user/purchaser/purchaseRecord");
        modelAndView.addObject("list", purchases);
        System.out.println(purchases);
        return modelAndView;
    }

    /**
     * 销售记录展示
     *
     * @return 销售记录展示页面
     */
    // 接收登录表单请求
    @RequestMapping("/doSellRecord")
    public ModelAndView doSellRecord() {
        ModelAndView modelAndView = new ModelAndView();
        List<Sell> sells = productService.showSellRecord();
        modelAndView.setViewName("user/seller/sellRecord");
        modelAndView.addObject("list", sells);
        System.out.println(sells);
        return modelAndView;
    }

    /**
     * 商品库存展示(仅用于管理员修改)
     *
     * @return 商品库存列表页面
     */
    // 接收登录表单请求
    @RequestMapping("/doListOfInventory")
    public ModelAndView doListOfInventory() {
        ModelAndView modelAndView = new ModelAndView();
        List<Inventory> inventory = productService.showInventory();
        modelAndView.setViewName("user/admin/admin_inventory_update");
        modelAndView.addObject("list", inventory);
        System.out.println(inventory);
        return modelAndView;
    }

    /**
     * 商品库存展示（仅用于添加库存）
     *
     * @return 商品库存列表页面
     */
    // 接收登录表单请求
    @RequestMapping("/doListOfInventoryAdd")
    public ModelAndView doListOfInventoryAdd() {
        ModelAndView modelAndView = new ModelAndView();
        List<Inventory> inventory = productService.showInventory();
        modelAndView.setViewName("user/admin/product_purchase");
        modelAndView.addObject("list", inventory);
        System.out.println(inventory);
        return modelAndView;
    }

    /**
     * 商品库存展示（仅用于减少）
     *
     * @return 商品库存列表页面
     */
    // 接收登录表单请求
    @RequestMapping("/doListOfInventorySell")
    public ModelAndView doListOfInventorySell() {
        ModelAndView modelAndView = new ModelAndView();
        List<Inventory> inventory = productService.showInventory();
        modelAndView.setViewName("user/admin/product_sell");
        modelAndView.addObject("list", inventory);
        System.out.println(inventory);
        return modelAndView;
    }

    /**
     * 商品供应商获取
     *
     * @return 转到采购页
     */

    // 接收修改id
    @RequestMapping("/doShowSupplier")
    public ModelAndView doShowSupplier() {
        List<Supplier> supplier = productService.showSupplier();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("supplier", supplier);
        modelAndView.setViewName("user/admin/supplier_list");
        return modelAndView;
    }

    /**
     * 展示用于更新的供货商列表
     *
     * @return 转到供货商列表
     */
    // 接收修改id
    @RequestMapping("/doShowSupplierForUpdate")
    public ModelAndView doShowSupplierForUpdate() {
        List<Supplier> supplier = productService.showSupplier();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("supplier", supplier);
        modelAndView.setViewName("user/admin/supplierUpdate_list");
        return modelAndView;
    }

    /**
     * 根据商品供应商编号获取其对应产品采购列表
     *
     * @return 转到采购页
     */
    // 接收修改id
    @RequestMapping("/doChooseProductOfSupplier")
    public ModelAndView doChooseProductOfSupplier(HttpServletRequest request) {
        Supplier supplier = productService.selectSupplierBySupplierId(Integer.parseInt(request.getParameter("supplier_id")));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("supplier_id", supplier.getSupplier_id());
        modelAndView.addObject("supplier_name", supplier.getSupplier_name());
        modelAndView.setViewName("user/admin/product_purchase_add");
        return modelAndView;
    }


    /**
     * 根据供货商编号进货
     * @param productAndSuppliers 产品和供货商实体
     * @param request 供货商编号
     * @return 返回至商品视图
     * @throws ParseException 异常
     */
    @RequestMapping("/doPurchaseAdd")
    public ModelAndView doPurchaseAdd(ProductAndSupplier productAndSuppliers, HttpServletRequest request) throws ParseException {
        SimpleDateFormat queueDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = queueDateFormat.format(new Date());
        Date createTime = queueDateFormat.parse(time);
        Supplier supplier = productService.selectSupplierBySupplierId(Integer.parseInt(request.getParameter("supplier_id")));
        MsgResult msgResult = productService.insertProduct(productAndSuppliers.getProduct_name(), productAndSuppliers.getSpecification(), productAndSuppliers.getPurchase_price(), productAndSuppliers.getSelling_price(), productAndSuppliers.getUnit(), supplier.getSupplier_name(), createTime);
        //添加关系
        ProductAndSupplierRelation productAndSupplierRelation = new ProductAndSupplierRelation();
        productAndSupplierRelation.setSupplier_id(supplier.getSupplier_id());
        productAndSupplierRelation.setProduct_id((Integer) msgResult.getContent());
        productService.insertProductAndSupplierRelation(productAndSupplierRelation);
        //添加入库
        Inventory inventory = new Inventory();
        inventory.setProduct_id((Integer) msgResult.getContent());
        inventory.setProduct_name(productAndSuppliers.getProduct_name());
        inventory.setProduct_inventory(0);
        inventory.setSupplier_id(supplier.getSupplier_id());
        inventory.setSupplier_name(supplier.getSupplier_name());
        productService.insertProductInInventory(inventory);

        return new ModelAndView("redirect:/doListOfProduct");
    }

    // 接收商品添加表单请求
    @RequestMapping("/doAjaxInsertProductInBatches")
    @ResponseBody
    public MsgResult doAjaxInsertProductInBatches(@RequestBody List<Product> products) throws ParseException {
        SimpleDateFormat queueDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = queueDateFormat.format(new Date());
        Date createTime = queueDateFormat.parse(time);
        MsgResult msgResult = new MsgResult();
        try {
            for (Product product : products) {
                System.out.println("product" + product.toString());
                productService.insertProduct(product.getProduct_name(), product.getSpecification(), product.getPurchase_price(), product.getSelling_price(), product.getUnit(), product.getSupplier_name(), createTime);
            }
            msgResult.setFlag(1);
            msgResult.setMsg("批量新增成功");
        } catch (Exception e) {
            msgResult.setFlag(0);
            msgResult.setMsg("批量新增失败");
            msgResult.setContent(e.getMessage());
        }

        return msgResult;
    }

    // 接收添加商品供应商请求
    @RequestMapping("/doAjaxInsertSupplierInBatches")
    @ResponseBody
    public MsgResult doAjaxInsertSupplierInBatches(@RequestBody List<Supplier> Suppliers) throws ParseException {
//        SimpleDateFormat queueDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time = queueDateFormat.format(new Date());
//        Date createTime = queueDateFormat.parse(time);
        MsgResult msgResult = new MsgResult();
        try {
            for (Supplier supplier : Suppliers) {
                System.out.println("supplier" + supplier.toString());
                Supplier supplier1 = new Supplier();
                supplier1.setSupplier_name(supplier.getSupplier_name());
                supplier1.setAddress(supplier.getAddress());
                supplier1.setPhone(supplier.getPhone());
                productService.insertSupplier(supplier1);
            }
            msgResult.setFlag(1);
            msgResult.setMsg("批量新增成功");
        } catch (Exception e) {
            msgResult.setFlag(0);
            msgResult.setMsg("批量新增失败");
            msgResult.setContent(e.getMessage());
        }

        return msgResult;
    }

    /**
     * 单个商品删除
     *
     * @param id 商品编号
     * @return 视图重定向至商品列表
     */
    // 接收删除请求
    @RequestMapping("/doDeleteProduct")
    public ModelAndView doDeleteProduct(int id) {
        boolean result = productService.deleteProduct(id);
        if (result) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
        return new ModelAndView("redirect:/doListOfProduct");
    }

    /**
     * 单个供应商删除
     * 同时根据供应商id删除其在商品表中的所有相关商品
     *
     * @param id 商供应商编号
     * @return 视图重定向至商品列表
     */
    // 接收删除请求
    @RequestMapping("/doDeleteSupplier")
    public ModelAndView doDeleteSupplier(int id) {
        Supplier supplier = productService.selectSupplierBySupplierId(id);
        boolean result1 = productService.deleteProductBySupplierName(supplier);
        boolean result = productService.deleteSupplier(id);
        if (result && result1) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
        return new ModelAndView("redirect:/doShowSupplierForUpdate");
    }

    /**
     * 商品批量删除
     *
     * @param ids id集合
     * @return 视图重定向至商品列表
     */
    @RequestMapping("/doDeleteProductInBatches")
    public ModelAndView doDeleteProductInBatches(Integer[] ids) {
        ModelAndView modelAndView = new ModelAndView();
        System.out.println(ids);
        Product product = new Product();
        for (Integer id : ids) {
            product.setProduct_id(id);
            boolean result = productService.deleteProduct(product.getProduct_id());
            System.out.println("successfully get product:" + id);
            if (result) {
                modelAndView.addObject("product", product);
                modelAndView.setViewName("product_list");
                System.out.println("successfully delete product:" + id);
            } else {
                System.out.println("fail to delete product:" + id);
            }
        }
        return new ModelAndView("redirect:/doListOfProduct");
    }

    /**
     * 单个采购记录删除
     *
     * @param id 采购编号
     * @return 视图重定向至采购记录列表
     */
    // 接收删除请求
    @RequestMapping("/doDeletePurchaseRecord")
    public ModelAndView doDeletePurchaseRecord(int id) {
        boolean result = productService.deletePurchaseRecord(id);
        if (result) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
        return new ModelAndView("redirect:/doPurchaseRecord");
    }

    /**
     * 单个销售记录删除
     *
     * @param id 销售编号
     * @return 视图重定向至销售记录列表
     */
    // 接收删除请求
    @RequestMapping("/doDeleteSellRecord")
    public ModelAndView doDeleteSellRecord(int id) {
        boolean result = productService.deleteSellRecord(id);
        if (result) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
        return new ModelAndView("redirect:/doSellRecord");
    }

    /**
     * 商品修改id获取
     *
     * @return 转到修改页
     */

    // 接收修改id
    @RequestMapping("/doUpdateProductId")
    public ModelAndView doUpdateProductId(HttpServletRequest request) {
        String id = request.getParameter("id");
        Product product = productService.selectProductById(Integer.parseInt(id));
        request.setAttribute("product", product);
        System.out.println("xiugai" + id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("list", product);
        modelAndView.setViewName("user/admin/admin_product_update");
        return modelAndView;
    }

    /**
     * 商品修改
     *
     * @return 视图重定向至商品列表
     */
    // 接收修改请求
    @RequestMapping("/doUpdateProduct")
    public ModelAndView doUpdateProduct(Product param) {
        ModelAndView modelAndView = new ModelAndView();
        Product product = new Product();
        product.setProduct_id(param.getProduct_id());
        product.setProduct_name(param.getProduct_name());
        product.setSpecification(param.getSpecification());
        product.setPurchase_price(param.getPurchase_price());
        product.setSelling_price(param.getSelling_price());
        product.setUnit(param.getUnit());
        product.setSupplier_name(param.getSupplier_name());
        System.out.println("xiugaizhixing" + product);
        boolean flag = productService.updateProduct(product);
        if (flag) {
            System.out.println("xgzx--" + flag);
            modelAndView.addObject("list", product);
            modelAndView.setViewName("redirect:/doListOfProduct");
        } else {
            System.out.println("修改失败");
        }
        return modelAndView;
    }

    /**
     * 供货商信息修改
     *
     * @return 视图重定向至商品列表
     */
    // 接收修改请求
    @RequestMapping("/doUpdateSupplier")
    public ModelAndView doUpdateSupplier(Supplier param) {
        ModelAndView modelAndView = new ModelAndView();
        Supplier supplier = new Supplier();
        supplier.setSupplier_id(param.getSupplier_id());
        supplier.setSupplier_name(param.getSupplier_name());
        supplier.setAddress(param.getAddress());
        supplier.setPhone(param.getPhone());
        System.out.println("xiugaizhixing" + supplier);
        boolean flag = productService.updateSupplier(supplier);
        if (flag) {
            System.out.println("xgzx--" + flag);
            modelAndView.addObject("list", supplier);
            modelAndView.setViewName("redirect:/doShowSupplierForUpdate");
        } else {
            System.out.println("修改失败");
        }
        return modelAndView;
    }

    /**
     * 单个商品库存修改
     *
     * @param param 商品编号
     * @return 视图重定向至商品库存列表
     */
    // 接收删除请求
    @RequestMapping("/doUpdateInventory")
    public ModelAndView doUpdateInventory(Inventory param, HttpServletRequest request) {
        Inventory inventory = new Inventory();
        inventory.setProduct_id(Integer.parseInt(request.getParameter("id")));
        inventory.setProduct_inventory(param.getProduct_inventory());
        boolean result = productService.updateInventory(inventory);
        if (result) {
            System.out.println("修改成功");
        } else {
            System.out.println("修改失败");
        }
        return new ModelAndView("redirect:/doListOfInventory");
    }

    /**
     * 单个商品库存增加
     *
     * @param param 商品编号
     * @return 视图重定向至商品库存列表
     */
    // 接收增加请求
    @RequestMapping("/doAddInventory")
    public ModelAndView doAddInventory(Inventory param, HttpServletRequest request) throws ParseException {
        SimpleDateFormat queueDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = queueDateFormat.format(new Date());
        Date createtime = queueDateFormat.parse(time);
        Inventory inventory = new Inventory();
        inventory.setProduct_id(Integer.parseInt(request.getParameter("id")));
        //查询原商品库存
        Inventory inventory1 = productService.selectInventoryById(Integer.parseInt(request.getParameter("id")));
        //添加后库存数量
        int newInventory = (int) (inventory1.getProduct_inventory() + param.getProduct_inventory());
        Product product = productService.selectProductById(inventory1.getProduct_id());
        inventory.setProduct_inventory(newInventory);
        HttpSession session = request.getSession();
        //生成商品采购表
        Purchase purchase = new Purchase();
        purchase.setProduct_id(Integer.parseInt(request.getParameter("id")));
        purchase.setProduct_name(inventory1.getProduct_name());
        purchase.setSupplier_id(inventory1.getSupplier_id());
        purchase.setSupplier_name(inventory1.getSupplier_name());
        purchase.setPurchaser_id((Integer) session.getAttribute("id"));
        purchase.setPurchase_price(product.getPurchase_price());
        purchase.setQuantity(param.getProduct_inventory());
        purchase.setPurchase_time(createtime);
        boolean rssult1= productService.insertProduct_purchase(purchase);
        //更新商品库存表
        boolean result = productService.updateInventory(inventory);
        if (result && rssult1) {
            System.out.println("修改成功");
        } else {
            System.out.println("修改失败");
        }
        return new ModelAndView("redirect:/doListOfInventory");
    }

    /**
     * 单个商品库存减少
     *
     * @param param 商品编号
     * @return 视图重定向至商品库存列表
     */
    // 接收增加请求
    @RequestMapping("/doSellInventory")
    public ModelAndView doSellInventory(Inventory param, HttpServletRequest request) throws ParseException {
        SimpleDateFormat queueDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = queueDateFormat.format(new Date());
        Date createtime = queueDateFormat.parse(time);
        Inventory inventory = new Inventory();
        inventory.setProduct_id(Integer.parseInt(request.getParameter("id")));
        //查询原商品库存
        Inventory inventory1 = productService.selectInventoryById(Integer.parseInt(request.getParameter("id")));
        int newInventory = (int) (inventory1.getProduct_inventory() - param.getProduct_inventory());
        Product product = productService.selectProductById(inventory1.getProduct_id());
        if (newInventory > 0) {
            inventory.setProduct_inventory(newInventory);
            HttpSession session = request.getSession();
            //生成商品销售表
            Sell sell = new Sell();
            sell.setProduct_id(Integer.parseInt(request.getParameter("id")));
            sell.setProduct_name(inventory1.getProduct_name());
            sell.setSeller_id((Integer) session.getAttribute("id"));
            sell.setPrice(product.getSelling_price());
            sell.setQuantity(param.getProduct_inventory());
            sell.setSale_time(createtime);
            boolean result1 = productService.insertProduct_sell(sell);
            //更新商品库存表
            boolean result = productService.updateInventory(inventory);
            if (result) {
                System.out.println("修改成功");
            } else {
                System.out.println("修改失败");
            }
        }
        System.out.println("库存不足！");
        return new ModelAndView("redirect:/doListOfInventory");
    }
}
